import dd from "dingtalk-jsapi"
import {useNavigate, useSearchParams} from "react-router-dom";
import {Loading} from "@alifd/next";
import './index.css'

const Login = () => {
    const [params] = useSearchParams();
    const navigate = useNavigate();
    console.log(dd.env.platform);//浏览器返回"notInDingTalk"
    if (dd.env.platform === "notInDingTalk") {
        localStorage.clear();
        window.location.href = "https://login.dingtalk.com/oauth2/auth?" +
            `redirect_uri=` + encodeURIComponent(`${window.appConfig.homeAddress}/getUserInfo`) +
            `&response_type=code` +
            `&client_id=${window.appConfig.SUITE_KEY}` +
            `&scope=openid%20corpid` +
            `&prompt=consent`
    } else {
        const corpId = params.get("corpId");
        dd.ready(() => {
            dd.runtime.permission.requestAuthCode({
                corpId: corpId,
                onSuccess: (info) => {
                    const authCode = info.code;
                    const myHeaders = new Headers();
                    myHeaders.append("Content-Type", "application/json");

                    const requestOptions = {
                        method: 'GET',
                        headers: myHeaders,
                        redirect: 'follow'
                    };

                    fetch(`${window.appConfig.servicePath}/authByDing?authCode=${authCode}&corpId=${corpId}`, requestOptions)
                        .then(response => response.json()
                            .then(result => {
                                console.log("result", result)
                                localStorage.setItem("icip-dingtalk-loginUser", JSON.stringify(result.loginUser))
                                localStorage.setItem("icip-dingtalk-corpId", result.corpId)
                                navigate("/home/project")
                            }))
                        .catch(error => console.log('error', error));
                    return;
                }
            })
        })
    }

    const indicator = (
        <div className="load-container load1">
            <div className="loader">loading...</div>
        </div>
    );
    return (
        <Loading indicator={indicator}></Loading>
    );
};

export default Login;